package com.duan.boot.service.impl;

import com.duan.boot.entity.News;
import com.duan.boot.entity.Task;
import com.duan.boot.mapper.NewsMapper;
import com.duan.boot.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class NewsServiceImpl implements NewsService {
    private final NewsMapper newsMapper;

    @Autowired
    public NewsServiceImpl(NewsMapper newsMapper) {
        this.newsMapper = newsMapper;
    }
    @Override
    public News getById(Long id) {
        return newsMapper.getById(id);
    }

    @Override
    public Integer insertOaNews(News news){
        return newsMapper.insertOaNews(news);
    }

    @Override
    public List<News> findAll() {
        return newsMapper.findAll();
    }

    @Override
    public List<News> getByType(Integer newsType) {
        List<Integer> list = new ArrayList<>();
        list.add(0);
        list.add(1);
        if (list.contains(newsType)){
            return newsMapper.getByType(newsType);
        }
        return null;
    }

    @Override
    public Integer getNumberOfNews() {
        return findAll().size();
    }

    @Override
    public List<News> pagedQuery(Integer page, Integer numberOfPage) {
        Map<Integer, List<News>> map = new HashMap<>();
        //查询总的页数
        int totalPage = 0;
        if (getNumberOfNews()%numberOfPage==0){
            totalPage = getNumberOfNews()/numberOfPage;
        }else {
            totalPage = getNumberOfNews() / numberOfPage + 1;
        }
        //第一层循环就是每一页的下标
        for (int i = 0; i<totalPage; i++){
            //第二层循环就是获得当前页多有的元素
            List<News> list = new ArrayList<>();
            for (int j = i*numberOfPage;j<numberOfPage+i*numberOfPage; j++){
                if (j==findAll().size()){
                    break;
                }
                list.add(findAll().get(j));

            }
            map.put(i, list);
        }
        return map.get(page-1);
    }

    @Override
    public Integer pagedQueryPage(Integer numberOfPage) {
        int totalPage = 0;
        if (getNumberOfNews()%numberOfPage==0){
            totalPage = getNumberOfNews()/numberOfPage;
        }else {
            totalPage = getNumberOfNews() / numberOfPage + 1;
        }
        return totalPage;
    }
}
